﻿#region File Description
//  DomoBCI 
//  License: GNU/GPL
//  Developer: Federico Leonardo Motta
//  File description: This component handles files.
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
using SharedContent;
#endregion


namespace DomoBCI.Core.GameManager
{
    class FileManager
    {
        /// <summary>
        /// Il FileManager si occupa di caricare/salvare/cancellare file di testo/xml.
        /// Ad esempio i file con i profili degli utenti o i file opzioni.
        /// </summary>
        public void DoDelete(StorageDevice device, User user)
        {
            // Apro un container per lo storage.
            IAsyncResult result =
                device.BeginOpenContainer("Users", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = user.Nome + ".usr";

            // Controllo che il file esista.
            if (container.FileExists(filename))
                // Cancello il file
                container.DeleteFile(filename);
        }
        
        public void DoSave(StorageDevice device, User user)
        {
            if (user != null)
            {
                // Apro un container per lo storage.
                IAsyncResult result =
                    device.BeginOpenContainer("Users", null, null);

                // Wait for the WaitHandle to become signaled.
                result.AsyncWaitHandle.WaitOne();

                StorageContainer container = device.EndOpenContainer(result);

                // Close the wait handle.
                result.AsyncWaitHandle.Close();

                string filename = user.Nome + ".usr";

                // Controllo che il file esista.
                if (container.FileExists(filename))
                    // Se esiste lo cancello per ricrearlo da 0.
                    container.DeleteFile(filename);

                // Creo il file.
                Stream stream = container.CreateFile(filename);

                // Serializzo l'oggetto in formato XML.
                XmlSerializer serializer = new XmlSerializer(typeof(User));

                serializer.Serialize(stream, user);

                // Chiudo il file.
                stream.Close();

                // Disptruggo il container.
                container.Dispose();
            }
            
        }

        // Sovraccarico il metodo DoSave per funzionare con gli oggetti SharedOptions
        public void DoSave(StorageDevice device, SharedOptions opt) {
            XmlWriterSettings xmlSettings = new XmlWriterSettings();
            xmlSettings.Indent = true;
            // Creo l'oggetto XmlWriter che creerà/scriverà il file nella cartella dei contenuti (bin/debug/x86)
            using (XmlWriter xmlWriter = XmlWriter.Create("Content/Config.xml", xmlSettings))
            {
                // Creo un oggetto serializzatore
                XmlSerializer serializer = new XmlSerializer(typeof(SharedOptions));
                // Salvo l'oggetto SharedOptions formattato, coi tag xml
                serializer.Serialize(xmlWriter, opt);
            }
        }

        public List<User> GetUser(StorageDevice device)
        {
            User user;
            List<User> utenti=new List<User>();

            // Apro un container per lo storage.
            IAsyncResult result = device.BeginOpenContainer("Users", null, null);
            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();
            StorageContainer container = device.EndOpenContainer(result);
            String str = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)+"\\SavedGames\\DomoBCI\\Users\\Player1\\";
            try
            {
                string[] files = Directory.GetFiles(str);
                if (files.Length == 0)
                {
                    //se non ne contiene stampo a video un messaggio
                    Console.WriteLine("Nessun file");

                    //ed esco
                    return utenti;
                }
                result.AsyncWaitHandle.Close();
                //altrimenti per ogni file presente
                foreach (string file in files)
                {
                    string filename = System.IO.Path.GetFileName(file);
                    Console.WriteLine(System.IO.Path.GetFileName(file));
                    if (!container.FileExists(filename))
                    {
                        // If not, dispose of the container and return.
                        container.Dispose();
                        return null;
                    }
                    // Apro il file.
                    Stream stream = container.OpenFile(filename, FileMode.Open);

                    XmlSerializer serializer = new XmlSerializer(typeof(User));
                    user = (User)serializer.Deserialize(stream);
                    utenti.Add(user);
                    // Chiudo il file.
                    stream.Close();
                }
                // Disptruggo il container.
                container.Dispose();
            }catch(DirectoryNotFoundException){
                System.IO.Directory.CreateDirectory(str);
            }
            
            return utenti;
        }

        public SharedOptions GetOptions(StorageDevice device)
        {
            SharedOptions opt = new SharedOptions();
            XmlReaderSettings xmlSettings = new XmlReaderSettings();

            // Crewo un oggetto XmlReader 
            using (XmlReader xmlReader = XmlReader.Create("Content/Config.xml", xmlSettings)) {

                // Creo l'oggetto serializzatore
                XmlSerializer serializer = new XmlSerializer(typeof(SharedOptions));
                // Deserializzare il file Xml in un oggetto SharedOptions
                opt = (SharedOptions)serializer.Deserialize(xmlReader);
            }
    
            return opt;
        }
    }
}
